import { CommonSheet } from './index'


export type ElementRef = ':parent' | ':prev' | ':next' | `id:${string}`


/**
 * 所有 Shui 自定义元素的基类。
 */
export class ShElement extends HTMLElement {

    constructor() {
        super()
        this.attachShadow({ mode: 'open' })
        this.shadowRoot!.adoptedStyleSheets = [CommonSheet,]
    }

    public get $shadow(): ShadowRoot {
        return this.shadowRoot!
    }

    public getElement(ref: ElementRef): Element | null {
        let $: Element | null = null

        if (ref === ':parent') {
            $ = this.parentElement
        }
        else if (ref === ':prev') {
            $ = this.previousElementSibling
        }
        else if (ref === ':next') {
            $ = this.nextElementSibling
        }
        else if (ref.startsWith('id:')) {
            $ = this.$shadow.getElementById(ref.substring(3))
        }
        else {
            $ = this.$shadow.querySelector(ref)
        }

        return $
    }
}
customElements.define('sh-element', ShElement)